<style>
.menu-list li, ul li{
  padding: 8px 12px;
  border-bottom: 0px dashed #cacaca;
}

.menu-list li span {
  cursor: move;
}

.menu-list ul {
  margin-left: 6px;
  border-left: 0px dashed #aeaeae;
}

.menu-list .ui-sortable-helper {
  border: 0px;
}

.menu-list .ui-state-highlight {
  padding: 12px;
  margin: 5px;
  border: 1px solid #f0f0f0;
  background: #fafafa;
}
input[type="text"] {
  width: 230px;
}
</style>
<div class="box-page-container">
  <div class="box-page-header">
    <div class="title">Настройка навигации по сайту</div>
    <div class="other-controls right">
      <div class="btn"><button onclick="create(this); return false;" class="gray">Добавить пункт меню</button></div>
    </div>
  </div>
  <div class="box-page-body">
    <div class="box-message" id="message" style="display: none"></div>
    <div>
      <?php function renderMenu($items){ ?>
        <ul class="mConstr uz-sortable ui-sortable" id="mConstructor" style="margin:0;padding-left:20px;">
          <?php if(!empty($items)): foreach($items as $item): ?>
            <li id="mcid<?php echo $item['id'] ?>" class="mcItem uz-dropable ui-draggable">
              <div id="item">
                <span style="text-decoration: none; cursor: move; ">
                  <img alt="" class="mcOrder" style="vertical-align:-3px;cursor:crosshair;" border="0" src="http://s68.ucoz.net/img/fr/enc.gif" title="Вложить" width="15" height="15">
                  <span onmouseover="this.style.textDecoration='underline'" onmouseout="this.style.textDecoration='none'" class="textHolder ui-droppable" title="Переместить" style="cursor: move; "><? echo $item['label'] ?></span>
                  - <a id="item-link" href="<?php echo $item['uri'] ?>" target="_blank"><?php echo $item['uri'] ?></a>
                </span>
                <div id="control-item" style="float: right; display: none;">
                  <a href="#" onclick="editItem(this); return false;">Изменить</a>
                  <a href="#" onclick="deleteItem(this); return false;">Удалить</a>
                </div>
              </div>
              <?php if (count($item['pages'])){ renderMenu($item['pages']); } ?>
            </li>
          <?php endforeach; endif;?>
        </ul>
      <?php } ?>
      <?php renderMenu($this->items)?>
    </div>
  </div>
  <div class="box-page-footer">
    <div class="box-controls">
      <div class="right">
       	<div class="btn"><button onclick="save(this); return false;" class="primary">Сохранить</button></div>
       	<div class="btn"><button onclick="cancel(); return false;" class="gray">Отменить</button></div>
      </div>
      <div id="progress" class="progress ajax-preloader-base"></div>
      <div id="control_text" class="box-controls-text"></div>
      <div class="clear-fix"></div>
    </div>
  </div>
  <div class="clear-fix"></div>
</div>
<script src="/js/jquery/jquery.js"></script>
<script src="/js/jquery/jquery-ui.js"></script>
<script>
var newMenuItem = new goog.ui.Dialog(null, true);
itemContent = '<div class="box-message" id="new-item-message" style="display: none"></div><div class="form"><dt id="name-label"><label for="item-name" class="required">Название ссылки:</label></dt>';
itemContent+= '<dd id="name-element"><input type="text" name="item-name" id="item-name" value=""></dd>';
itemContent+= '<dt id="address-label"><label for="item-address" class="required">Адресс страницы:</label></dt>';
itemContent+= '<dd id="address-element"><input type="text" name="item-address" id="item-address" value=""></dd></div>'
newMenuItem.setContent(itemContent);
newMenuItem.setTitle('Новая ссылка');
newMenuItem.setButtonSet(
	new goog.ui.Dialog.ButtonSet()
	.addButton({key: 'create', caption: 'Создать'}, true)
	.addButton({key: 'cancel', caption: 'Отменить'}, false, true)
);

function create() {
	newMenuItem.setVisible(true);
}

function cancel() {
	window.location = window.location;
}

function editItem(el) {
	var i = new goog.ui.Dialog(null, true);
	var parent = $(el).parent().parent().parent();
	var name = $('span.textHolder:first', parent).text();
	var url = $("#item-link", parent).attr('href');
	var itemContent = '<div class="box-message" id="edit-item-message" style="display: none"></div><div id="edit-item" class="form"><dt id="name-label"><label for="item-name" class="required">Название ссылки:</label></dt>';
	itemContent+= '<dd id="name-element"><input type="text" name="item-name" id="item-name" value="'+name+'"></dd>';
	itemContent+= '<dt id="address-label"><label for="item-address" class="required">Адресс страницы:</label></dt>';
	itemContent+= '<dd id="address-element"><input type="text" name="item-address" id="item-address" value="'+url+'"></dd></div>';
	i.setContent(itemContent);
	i.setTitle('Изменить ссылку');
	i.setButtonSet(
		new goog.ui.Dialog.ButtonSet()
		.addButton({key: 'save', caption: 'Сохранить'}, true)
		.addButton({key: 'cancel', caption: 'Отменить'}, false, true)
	);
	i.setVisible(true);
	goog.events.listen(i, goog.ui.Dialog.EventType.SELECT, function(e){
		if (e.key == 'save') {
			var msgBox = goog.dom.$('edit-item-message'),
			itemName = $('#item-name', '#edit-item'),
			itemAddr = $('#item-address', '#edit-item');
			if (!itemName.val() || !itemAddr.val()) {
				msgBox.innerHTML = '<p>Все поля обязательны для заполнения.</p>';
				fx = new goog.fx.dom.FadeInAndShow(msgBox, 200);
				fx.play();
				if (!itemName.val()) {
					itemName.focus();
				} else {
					itemAddr.focus();
				}
				return false;
			}
			$('span.textHolder:first', parent).text(itemName.val());
			$("#item-link:eq(0)", parent).attr('href', itemAddr.val()).text(itemAddr.val());
		}
		$('.modal-dialog-bg').remove();
		$('.modal-dialog').remove();
	});
}

function deleteItem(el) {
	$(el).parent().parent().parent().remove();
}

goog.events.listen(newMenuItem, goog.ui.Dialog.EventType.SELECT, function(e){
	if (e.key == 'create') {
		var msgBox = goog.dom.getElement('new-item-message'),
			itemName = goog.dom.getElement('item-name'),
			itemAddr = goog.dom.getElement('item-address');
		if (!itemName.value || !itemAddr.value) {
			msgBox.innerHTML = '<p>Все поля обязательны для заполнения.</p>';
			fx = new goog.fx.dom.FadeInAndShow(msgBox, 200);
			fx.play();
			if (!itemName.value) {
				itemName.focus();
			} else {
				itemAddr.focus();
			}
			return false;
		}
		var id_ = $('#mConstructor').parent().find('li').length;
		var id = (id_ != 0) ? id_ + 1 : 1;
		$('#mConstructor').parent().find('li').each(function(){
			var curr_id = $(this).attr('id');
			if (curr_id == 'mcid' + id) {
				id = id + 1;
			}
		});
        var html = '<li id="mcid'+id+'" class="mcItem uz-dropable ui-draggable">';
        html += '<div id="item"><span style="text-decoration: none; cursor: move; ">';
        html += '<img alt="" class="mcOrder" style="vertical-align:-3px;cursor:crosshair;" border="0" src="http://s68.ucoz.net/img/fr/enc.gif" title="Вложить" width="15" height="15">';;
        html += '<span onmouseover="this.style.textDecoration=\'underline\'" onmouseout="this.style.textDecoration=\'none\'" class="textHolder ui-droppable" title="Переместить" style="cursor: move; ">'+itemName.value+'</span>';
		html += ' - <a id="item-link" href="'+itemAddr.value+'" target="_blank">'+itemAddr.value+'</a></span>';
		html += '<div id="control-item" style="float: right; display: none;"><a href="#" onclick="editItem(this); return false;">Изменить</a><a href="#" onclick="deleteItem(this); return false;">Удалить</a></div></div></li>';
		$('#mConstructor').append(html);
		itemControl();
	}
});

function itemControl() {	
	sortTree('#mConstructor', '.uz-dropable', '.textHolder');
	$('#mConstructor #item').hover(
		function() {
			$(this).find('#control-item').fadeIn(100);
		},
		function() {
			$(this).find('#control-item').fadeOut(100);
		}
	);
}
var control_text = goog.dom.getElement('control_text');
var progress = goog.dom.getElement('progress');
function save(el) {
	goog.style.showElement(control_text, false);
	goog.style.setStyle(progress, 'display', 'block');
	el.disable = true;
	goog.dom.classes.add(el, 'disabled');
	data = [];
	getDataFromUL('#mConstructor');
	$.ajax({
		"url": "/cp/settings/nav.save",
		"type": "POST",
		"dataType": "json",
		"data": {"items": data},
		"success": function(response) {
			goog.style.showElement(control_text, true);
			goog.style.setStyle(progress, 'display', 'none');
			goog.dom.classes.remove(el, 'disabled');
			el.disable = false;
			control_text.innerHTML = 'Пункты меню успешно сохранены.';
			setTimeout(function(){
				goog.style.showElement(control_text, false);
			}, 1000);
		},
		"error": function(response) {
			goog.style.showElement(control_text, true);
			goog.style.setStyle(progress, 'display', 'none');
			goog.dom.classes.remove(el, 'disabled');
			el.disable = false;
			control_text.innerHTML = 'Во время обработки запроса, возникли ошибки.';
			setTimeout(function(){
				goog.style.showElement(control_text, false);
			}, 4000);
		}
	});
}

var myData;
var sorted = false;
var out_str = '';
var cBoxCh;
var i_d, drag_class, drop_class, drag_handle;

function onDrop(e, ui, copy){
    var c_t = '';
    var u_d = '';
    if (!copy) {
        c_t = $(e.target);
        u_d = ui.draggable;
    }
    else {
        c_t = $(e);
        u_d = $(ui);
    }
    c_tp = c_t.parents('li');
    c_ts = c_t.parent('span').parent('div');
    c_t.removeClass('dropOver');
    if (c_tp.attr("id") == $(u_d).attr("id") || $('#' + c_tp.attr("id"), $(u_d)).length == 1) {
        return;
    }
    subbranch = $('ul', c_ts.parent('li'));
    if (subbranch.size() === 0) {
        c_ts.after('<ul class="uz-sortable mConstr"></ul>');
        subbranch = $('ul', c_tp);
    }
    oldParent = $(u_d).parent();
    subbranch.eq(0).append($(u_d));
    oldBranches = $('li', oldParent);
    if (oldBranches.size() === 0) {
        $(oldParent).remove();
    }
}

var x = 0;
function getDataFromUL(el){
    var items = $(el).children('li');
    var tit_ = '';
    var cls_ = '';
    var url_ = '';
    var r = [];
    if (items.length > 0) {
        for (var i = 0; i < items.length; i++) {
            var result = {'id':'', 'parent_id':'', 'label':'', 'uri':'', 'pages': []};
            out_str += $(items[i]).attr('id') + '|';
            result.id = $(items[i]).attr('id');
            if (typeof $(items[i]).parents('li').attr('id') != 'undefined') {
                out_str += $(items[i]).parents('li').attr('id') + '|';
                result.parent_id = $(items[i]).parents('li').attr('id');
            }
            else {
                out_str += '|';
                result.parent_id = 0;
            }
            
            tit_ = $('span.textHolder:first', items[i]).text().replace(/\|/g, "&#124;").replace(/\`/g, "&#96;");
            out_str += tit_ + '|';
            result.label = tit_;
            url_ = $("a", items[i]).attr('href');
            out_str += url_ + '|';
            result.uri = url_;
            var c_i = $(items[i]).find('>ul');
            if (c_i.length > 0) {
                result.pages = getDataFromUL(c_i);
            }
            data.push(result);
            x++;
        }
    }
}

function saveTree(el){
    out_str = '';
    getDataFromUL(el);
    return out_str;
}

function saveBoxes(){

	$(i_d+' input').removeClass('cbSec');
	$(i_d + ' input.sel:checked').parent('div').parent('li').each(function(i,item){
	        $(item).find('input:not(:first)').addClass('cbSec');
	    })
	
	cBoxCh = $(i_d + ' input.sel:checked:not(.cbSec)').parent('div').parent('li');
	$(i_d+' input').removeClass('cbSec');

    if (cBoxCh.length) {
		$('#sBoxCopyCnt').text('(' + $(i_d + ' input.sel:checked').length + ')').show();
		$('.mcCopy',i_d).remove();
		$(i_d + ' li>div>span').append('<a style="display:none" class="mcCopy mcBut" onclick="return pasteBoxes(this);" href="javascript://"/>');
		$(i_d + ' li>div').hover(
			function(){
				$('.mcCopy',this).show();
			},function(){
				$('.mcCopy',this).hide();
			});
	}
	$('#cats-copy-cnt').text(cBoxCh.length ? '('+cBoxCh.length+')' : '');
}

function sortTree(id, drag_class, drop_class, drag_handle){
    i_d = id;
    tree = $(i_d);
    if (typeof drag_handle == 'undefined') {
        drag_handle = drag_class;
    }
    

    $('#mConstructor').sortable({
        containment: "document",
        cursorAt: {
            left: 5
        },
        tollerance: 'pointer',
        forcePlaceholderSize: true,
        start: function(e, ui){
            sorted = true;
            ui.placeholder.css('width', ui.helper.width());
            ui.placeholder.css('height', ui.helper.height());
            $(drop_class).droppable('disable');
        },
        stop: function(e, ui){
            sorted = false;
        },
        items: 'li',
        handle: 'span.textHolder',
        helper: function(){
            return $(document.createElement('div')).css({
                'width': '30px',
                'height': '15px',
                'background': '#fff',
                'border': '1px solid black',
                'padding': '5px'
            }).html('<span>Move</span>').appendTo("body")[0];
        }
    });
    
    $(drop_class).droppable({
        containment: "document",
        accept: drag_class,
        tollerance: 'pointer',
        refreshPositions: true,
        cursorAt: {
            left: 5
        },
        over: function(e, ui){
            if (!sorted) {
                $(e.target).addClass('dropOver');
            }
        },
        out: function(e, ui){
            if (!sorted) {
                $(e.target).removeClass('dropOver');
            }
        },
        drop: function(e, ui){
            onDrop(e, ui, false);
        }
    });
    
    $(drag_handle).hover(function(){
        $(this).find('span').css('cursor', 'move');
    }, function(){
        $(this).find('span').css('cursor', 'normal');
    });
    
    $.extend($.ui.draggable.prototype, (function(orig){
        return {
            _mouseCapture: function(event){
                var result = orig.call(this, event);
                if (result && $.browser.msie) {
                    event.stopPropagation();
                }
                return result;
            }
        };
    })($.ui.draggable.prototype["_mouseCapture"]));

    $('li' + drag_class).draggable({
        containment: "document",
        start: function(e, ui){
            $(drop_class).droppable('enable');
        },
        handle: 'img.mcOrder',
        cursorAt: {
            left: 5
        },
        helper: function(){
            return $(document.createElement('div')).css({
                'background': '#fff',
                'border': '1px solid black',
                'padding': '5px'
            }).html('<span>...</span>').appendTo("body")[0];
        }
    });
}

function pasteBoxes(where){
    var e = $(where).parent().find('.textHolder');
 	$(cBoxCh).each(function(i, item){
        onDrop(e, item, true);
    });
	$(where).parent('span').css('textDecoration','none');
	$('.mcCopy').remove();
    $('input.sel',i_d).attr('checked', false);
	$('#h_inpt243').val('');
	$('#sBoxCnt').text('');
	$('#sBoxCopyCnt').text('');
	$('#cats-copy-cnt').text('');
    cBoxCh = '';
}

itemControl();
</script>
